package com.ztsoft.user.service.project.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.common.exception.CustomException;
import com.ztsoft.user.mapper.project.ChooseMapper;
import com.ztsoft.user.mapper.project.ProjectMapper;
import com.ztsoft.user.pojo.entity.project.*;
import com.ztsoft.user.pojo.entity.user.SysRole;
import com.ztsoft.user.pojo.entity.user.SysUser;
import com.ztsoft.user.pojo.entity.user.SysUserDemand;
import com.ztsoft.user.pojo.enums.ResultCode;
import com.ztsoft.user.pojo.vo.PageData;
import com.ztsoft.user.pojo.vo.PageInfo;
import com.ztsoft.user.pojo.vo.project.*;
import com.ztsoft.user.service.project.*;
import com.ztsoft.user.service.user.SysUserDemandService;
import com.ztsoft.user.service.user.SysUserService;
import com.ztsoft.user.utils.*;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChooseServiceImpl extends ServiceImpl<ChooseMapper, Choose> implements ChooseService {

    @Value("${file.exportWord}")
    private String exportWord;
    @Value("${file.enclosureFile}")
    private String enclosureFile;
    @Resource
    private ZipUtils zipUtils;
    @Value("${file.bidResultTable2}")
    private String bidResultTable;

    @Value("${file.templateZip2}")
    private String templateZip;

    @Resource
    private SysUserService sysUserService;
    @Resource
    private ContactsService contactsService;
    @Resource
    private ConstructionService constructionService;
    @Resource
    private DemandUnitService demandUnitService;
    @Resource
    private AnswerQuoteService answerQuoteService;
    @Resource
    private SysUserDemandService sysUserDemandService;
    @Resource
    private ChooseConstructionService chooseConstructionService;
    @Resource
    private ProjectService projectService;
    @Resource
    private UserProjectService userProjectService;
    @Resource
    private UserQuoteService userQuoteService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private SecondBargainService secondBargainService;

    @Override
    public Result<Object> getProject(Integer currentPage, Integer pageSize, String name, String region, String infoNumber) {
        // 查找用户与项目关联关系
        SysUser loginUser = sysUserService.getUserInfo2().getSysUser();
        List<Project> projectList = projectMapper.queryBatch(loginUser.getUserId(),name,region,infoNumber);
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = getProjectResultMap(projectList);

        return Result.success(new PageData(result, new PageInfo(pageSize, currentPage,  projectList.size())));
    }

    @Override
    public Result<Object> getChoose(String pid, Integer currentPage, Integer pageSize) {
        // 获取用户信息
        SysUser sysUser = sysUserService.getUserInfo().getSysUser();
        Map<String, Object> queryMap = new HashMap<>();
        // 暂存状态订单
        queryMap.put("state", 0);
        queryMap.put("create_id", sysUser.getUserId());

        queryMap.put("pid", pid);
        // 分页查找登录用户创建的订单
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap);
        Page<Choose> page = new Page<>(currentPage, pageSize);
        Page<Choose> choosePage = page(page, queryWrapper);
        List<Choose> chooseList = choosePage.getRecords();

        if (chooseList.isEmpty()) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = getChooseResultMap(chooseList);

        return Result.success(new PageData(result, new PageInfo(pageSize, currentPage, (int) choosePage.getTotal())));
    }

    @Override
    public Result<Object> addChoose(String pid, String[] ids) {
        // 获取登录用户信息
        SysUser loginUser = sysUserService.getUserInfo().getSysUser();

        // 查询登录用户可用物资
        List<String> quoteIds = new ArrayList<>();
        List<UserQuote> userQuoteList = userQuoteService.list(new QueryWrapper<UserQuote>().eq("user_id", loginUser.getUserId()));
        userQuoteList.forEach(userQuote -> quoteIds.add(userQuote.getQuoteId()));

        if (ids.length > 1) {
            return Result.returnMsg("不同包不能多选", ResultCode.FAILED.getCode());
        }

        // 获取需添加的清单列表
        List<Choose> chooseList = new ArrayList<>();
        for (String id : ids) {
            // 当前选择物资清单
            AnswerQuote answerQuote = answerQuoteService.getById(id);

            // 添加订单，判断是否是同包物资
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("pid", pid);
            queryMap.put("state", 0);
            queryMap.put("create_id", loginUser.getUserId());
            QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
            queryWrapper.allEq(queryMap);
            List<Choose> chooses = list(queryWrapper);
            for (Choose choose : chooses) {
                if (!(choose.getPackageName().equals(answerQuote.getPackageName()))) {
                    return Result.returnMsg("添加订单信息和已添加订单信息不在同一包", ResultCode.FAILED.getCode());
                }
                if (!(choose.getSubcontracted().equals(answerQuote.getSubcontracted()))) {
                    return Result.returnMsg("添加订单信息和已添加订单信息不在同一标", ResultCode.FAILED.getCode());
                }
            }

            // 添加订单，判断所选择物资的是否为与用户可用
            if (!quoteIds.contains(id)) {
                return Result.returnMsg("无权限，请联系管理员", ResultCode.FAILED.getCode());
            }

            Choose choose = new Choose();
            BeanUtil.copyProperties(answerQuote, choose, "id");

            choose.setState(0);
            choose.setCreateId(loginUser.getUserId());
            chooseList.add(choose);
        }

        saveBatch(chooseList);

        return Result.success();
    }

    @Override
    public Result<Object> deleteChoose(String[] ids) {

        if (removeByIds(Arrays.asList(ids))) {
            for (String id : ids) {
                Map<String, Object> removeMap = new HashMap<>();
                removeMap.put("choose_id", id);
                chooseConstructionService.removeByMap(removeMap);
            }
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> deleteAll(String pid) {
        // 获取用户信息
        SysUser sysUser = sysUserService.getUserInfo().getSysUser();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("pid", pid);
        // 暂存状态订单
        queryMap.put("state", 0);
        queryMap.put("create_id", sysUser.getUserId());

        if (removeByMap(queryMap)) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> updateChoose(ChooseRequest chooseRequest) {
        String cType = chooseRequest.getChooseType();
        if ("劳务".equals(cType)) {
            cType = "安装";
        }

        if (chooseRequest.getPrice() == null || chooseRequest.getPrice() == 0.0) {
            return Result.returnMsg("请先填写金额", ResultCode.FAILED.getCode());
        }
        if (chooseRequest.getDiscountType() == null || "".equals(chooseRequest.getDiscountType())) {
            return Result.returnMsg("请先选择折扣类型", ResultCode.FAILED.getCode());
        }

        String[] ids = chooseRequest.getIds();

        if (ids.length > 1) {
            return Result.returnMsg("请选择单条信息填写", ResultCode.FAILED.getCode());
        }

        for (String id : ids) {
            Choose updateChoose = getById(id);
            String subcontracted = updateChoose.getSubcontracted();
            if (subcontracted.contains("（") && subcontracted.contains("）")) {
                String chooseType = subcontracted.substring(subcontracted.indexOf("（") + 1, subcontracted.lastIndexOf("）"));
                if (!cType.equals(chooseType)) {
                    return Result.returnMsg("分包类型选择不一致，请重新选择", ResultCode.FAILED.getCode());
                }
            }

            String bidDiscountRate = updateChoose.getBidDiscountRate();
            String shopBidDiscountRate = updateChoose.getShopBidDiscountRate();

            // 鹏润项目下单时间不能超过2023.3.24
            String dateStr = "2023-03-24";
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = format.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if ("e95aa0cf7cef8e0a789632aca4b3d202".equals(updateChoose.getPid()) && (ObjectUtil.isNotNull(chooseRequest.getMatchingTime()) && (chooseRequest.getMatchingTime().before(date)))) {
                return Result.returnMsg("下单时间不能填写2023年3月24日前", ResultCode.FAILED.getCode());
            }

            BeanUtil.copyProperties(chooseRequest, updateChoose, "ids");

            BigDecimal divide = new BigDecimal("100");
            String discountRate = "";
            if ("中标折扣率".equals(updateChoose.getDiscountType())) {
                if (ObjectUtil.isNull(bidDiscountRate)) {
                    return Result.returnMsg("该包没有中标折扣率", ResultCode.FAILED.getCode());
                }
                discountRate = bidDiscountRate.replace("%", "");
                updateChoose.setIsStatePrice(false);
            }
            if ("国网商城中标折扣率".equals(updateChoose.getDiscountType())) {
                if (ObjectUtil.isNull(shopBidDiscountRate)) {
                    return Result.returnMsg("该包没有国网商城中标折扣率", ResultCode.FAILED.getCode());
                }
                discountRate = shopBidDiscountRate.replace("%", "");
                updateChoose.setIsStatePrice(true);
            }
            BigDecimal rate = new BigDecimal(discountRate).divide(divide, 6, RoundingMode.CEILING);
            BigDecimal num = BigDecimal.valueOf(updateChoose.getNumbers());
            BigDecimal price = BigDecimal.valueOf(updateChoose.getPrice());

            updateChoose.setSubtotal(rate.multiply(num.multiply(price)));

            updateById(updateChoose);
        }

        return Result.success();
    }

    @Override
    public Result<Object> getContact() {
        Map<String, Object> resultMap = new HashMap<>();
        // 需求单位列表
        List<ProjectMeta> unitNameList = new ArrayList<>();
        // 联系人列表
        List<ProjectMeta> contactNameList = new ArrayList<>();
        // 收货人列表
        List<ProjectMeta> consigneeNameList = new ArrayList<>();

        // 获取登录用户信息
        String demandUnitName = getDemandUnitName();

        // 1、获取所有匹配的需求单位列表
        DemandUnit demandUnit = demandUnitService.getOne(new QueryWrapper<DemandUnit>().eq("demand_unit_name", demandUnitName));
        if (demandUnit == null) {
            // 1.1、如果该用户没有绑定导需求单位
            resultMap.put("unitNameList", Collections.emptyList());
            resultMap.put("contactNameList", Collections.emptyList());
            resultMap.put("consigneeNameList", Collections.emptyList());

            return Result.success(resultMap);
        }

        unitNameList.add(new ProjectMeta(demandUnit.getId(), demandUnit.getDemandUnitName()));

        // 2、根据需求单位id获取联系人
        List<Contacts> contactsList = contactsService.list(new QueryWrapper<Contacts>().eq("demand_unit_id", demandUnit.getId()));

        // 2.1、区分联系人与收货人
        contactsList.stream().filter(contacts -> "联系人".equals(contacts.getContactsType())).forEach(contacts -> contactNameList.add(new ProjectMeta(contacts.getTelephone(), contacts.getContactsName())));
        contactsList.stream().filter(contacts -> "收货人".equals(contacts.getContactsType())).forEach(contacts -> consigneeNameList.add(new ProjectMeta(contacts.getTelephone(), contacts.getContactsName())));

        resultMap.put("unitNameList", unitNameList);
        resultMap.put("contactNameList", contactNameList);
        resultMap.put("consigneeNameList", consigneeNameList);

        return Result.success(resultMap);
    }

    @Override
    public Result<Object> commitChoose(String pid) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
        String week = sdf.format(date);
        // if (week.equals("星期四") || week.equals("星期五")) {
        //     return Result.returnMsg("今天是：" + week + ",无法提交订单", ResultCode.FAILED.getCode());
        // }

        // 获取登录用户创建的暂存订单
        SysUser sysUser = sysUserService.getUserInfo().getSysUser();
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("state", 0);
        queryMap.put("pid", pid);
        queryMap.put("create_id", sysUser.getUserId());
        queryWrapper.allEq(queryMap);
        List<Choose> chooseList = list(queryWrapper);

        for (Choose choose : chooseList) {
            // 判断必填字段是否已填写
            if (choose.getProjectName() == null || choose.getDemandUnit() == null || choose.getPrice() == null || choose.getConsigneeName() == null) {
                return Result.returnMsg(ResultCode.WARNING.getMsg(), ResultCode.WARNING.getCode());
            }
            // 判断班组信息是否已填写
            List<ChooseConstruction> chooseConstructionList = chooseConstructionService.list(new QueryWrapper<ChooseConstruction>().eq("choose_id", choose.getId()));
            if (chooseConstructionList.isEmpty()) {
                return Result.returnMsg("班组人员信息未填写", ResultCode.WARNING.getCode());
            }
        }

        BigDecimal subtotal = new BigDecimal("0");
        for (Choose choose : chooseList) {
            subtotal = subtotal.add(choose.getSubtotal());
        }

        //************************************************判断是否超额********************************************************************************
        // 已匹配金额
        BigDecimal matchingQuota = new BigDecimal("0");
        // 待匹配金额
        BigDecimal waitMatchingQuota = new BigDecimal("0");

        Choose queryChoose = chooseList.get(0);
        // 预估金额
        Double estimatedAmount = Double.parseDouble(queryChoose.getEstimatedAmount());

        HashMap<String, Object> queryMap3 = new HashMap<>();
        queryMap3.put("subcontracted", queryChoose.getSubcontracted());
        queryMap3.put("package_name", queryChoose.getPackageName());
        queryMap3.put("company_name", queryChoose.getCompanyName());
        queryMap3.put("pid", pid);
        QueryWrapper<Choose> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.allEq(queryMap3).notIn("state", 0, -1).ne("is_cancel", 1);
        List<Choose> chooses = list(queryWrapper3);

        for (Choose choose : chooses) {
            if (choose.getState() == 999) {
                matchingQuota = matchingQuota.add(choose.getSubtotal());
            } else {
                waitMatchingQuota = waitMatchingQuota.add(choose.getSubtotal());
            }
        }

        // 查找额度
        QueryWrapper<AnswerQuote> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.allEq(queryMap3);
        AnswerQuote answerQuote = answerQuoteService.getOne(queryWrapper4);
        // 额度比例
        Double quota = answerQuote.getQuotaState() == 1 ? answerQuote.getQuotaMin() : (answerQuote.getQuotaState() == 2 ? answerQuote.getQuotaStandard() : answerQuote.getQuotaMax());

        BigDecimal mid = matchingQuota.add(waitMatchingQuota.add(subtotal));
        double es = estimatedAmount * quota / 100;
        if (mid.compareTo(BigDecimal.valueOf(es)) > 0) {
            return Result.returnMsg(ResultCode.NUMBER_WARNING.getMsg(), ResultCode.NUMBER_WARNING.getCode());
        }

        //************************************************判断是否超额********************************************************************************

        // 设置导出号
        int num;
        QueryWrapper<Choose> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.select("max(orders_number) as orders_number").eq("pid", pid);
        Choose choose2 = getOne(queryWrapper2);
        if (choose2 == null) {
            num = 0;
        } else {
            num = Integer.parseInt(choose2.getOrdersNumber());
        }

        // 设置订单id
        Calendar calendar = Calendar.getInstance();
        String orderId = StringTimeUtil.stringTime(date) + UUID.randomUUID().toString().replace("-", "").substring(1, 18);

        for (Choose choose : chooseList) {
            Choose choose1 = baseMapper.selectById(choose.getId());
            String orderName = choose1.getSubcontracted() + choose1.getCompanyName() + calendar.get(Calendar.YEAR) + (1 + calendar.get(Calendar.MONTH)) + calendar.get(Calendar.DATE) + date.getHours() + date.getMinutes() + date.getSeconds();

            String orderNum = String.format("%03d", ++num);

            StringBuilder supplyNumber = new StringBuilder();
            supplyNumber.append(choose.getSubcontract()).append(choose.getPackageName()).append("-");
            if ("000000".equals(choose.getBatch())) {
                supplyNumber.append("-").append(orderNum);
            } else {
                supplyNumber.append(choose.getBatch()).append(orderNum);
            }
            // 暂存0--》待审核1
            choose.setState(1);
            choose.setAlterationStatus(0);
            choose.setOrderId(orderId);
            choose.setOrderName(orderName);
            choose.setOrderTime(date);
            choose.setOrdersNumber(orderNum);
            choose.setSupplyNumber(supplyNumber.toString());
        }

        if (updateBatchById(chooseList)) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> getSelfChoose(String pid, Integer currentPage, Integer pageSize, Integer state, String orderId, String orderName, String batch, String projectName, Boolean cancel) {
        // 获取用户信息
        SysUser sysUser = sysUserService.getUserInfo().getSysUser();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("create_id", sysUser.getUserId());
        queryMap.put("order_id", orderId);
        queryMap.put("order_name", orderName);
        queryMap.put("batch", batch);
        queryMap.put("is_cancel", cancel);
        queryMap.put("project_name", projectName);

        if(state != 0){
            queryMap.put("state", state);
        }
        // 傻逼,智障,弱智,前后端2傻逼。state查全部不会给undefine？傻逼后端还傻逼去改！
//        if (state == 1) {
//            // 匹配人未提交状态订单
//            queryMap.put("state", 1);
//        } else if (state == 2) {
//            // 匹配人已提交状态订单
//            queryMap.put("state", 2);
//        } else if (state == 999) {
//            // 匹配人已审批状态订单
//            queryMap.put("state", 999);
//        } else if (state == -1) {
//            // 匹配人已审批状态订单
//            queryMap.put("state", -1);
//        }

        return returnChoose(pid, currentPage, pageSize, queryMap);
    }

    @Override
    public Result<Object> getOperationChoose(String pid, Integer currentPage, Integer pageSize, Integer type, String orderId, Integer type2, String orderName, String batch, String projectName, Boolean cancel, String demandUnit) {
        List<SysRole> roleList = sysUserService.getUserInfo().getRoleList();

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("order_id", orderId);
        queryMap.put("order_name", orderName);
        queryMap.put("batch", batch);
        queryMap.put("is_cancel", cancel);
        queryMap.put("project_name", projectName);
        queryMap.put("is_cancel_audit", type2);
        queryMap.put("demand_unit", demandUnit);

        if (roleList.stream().anyMatch(role -> role.getRoleName().contains("匹配人"))) {
            return getMatchingChoose(pid, currentPage, pageSize, type, queryMap);
        } else if (roleList.stream().anyMatch(role -> role.getRoleName().contains("审核人"))) {
            return getAuditChoose(pid, currentPage, pageSize, type, queryMap);
        } else if (roleList.stream().anyMatch(role -> role.getRoleName().contains("代理机构"))) {
            return getAgencyChoose(pid, currentPage, pageSize, type, queryMap);
        }

        return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
    }

    @Override
    public Result<Object> auditChoose(String orderId, String type, Choose requestChoose) {
        List<SysRole> roleList = sysUserService.getUserInfo().getRoleList();

        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<Choose> chooseList = list(queryWrapper);

        for (Choose choose : chooseList) {
            if (roleList.stream().anyMatch(role -> role.getRoleName().contains("匹配人"))) {
                if ("pass".equals(type)) {
                    if ("000000".equals(choose.getBatch()) || ObjectUtil.isNull(choose.getMatchTime())) {
                        return Result.returnMsg("未设置订单匹配批次和匹配时间", ResultCode.FAILED.getCode());
                    }
                    choose.setReason("");
                    choose.setIsCancelAudit(0);
                    choose.setState(2); // 提交到审核人未提交
                } else if ("noPass".equals(type)) {
                    choose.setState(-1);    // 驳回
                    choose.setReason(requestChoose.getReason());
                }
            } else if (roleList.stream().anyMatch(role -> role.getRoleName().contains("审核人"))) {
                if ("pass".equals(type)) {
                    if ("000000".equals(choose.getBatch()) || ObjectUtil.isNull(choose.getMatchTime())) {
                        return Result.returnMsg("未设置订单匹配批次和匹配时间", ResultCode.FAILED.getCode());
                    }

                    choose.setReason("");
                    choose.setIsCancelAudit(0);
                    choose.setState(999);   // 审核通过
                    if (choose.getAlterationStatus() == 2) {
                        choose.setAlterationStatus(1);
                    } else if (choose.getAlterationStatus() == 1) {
                        choose.setAlterationStatus(0);
                    }
                } else if ("noPass".equals(type)) {
                    choose.setState(1);  // 返回匹配人未提交
                    choose.setReason(requestChoose.getReason());
                    choose.setIsCancelAudit(1);// 审核人驳回
                }
            }
            updateById(choose);
        }
        return Result.success();
    }

    @Override
    public Result<Object> cancelChoose(String orderId, int type, MultipartFile fileList) {
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<Choose> chooseList = list(queryWrapper);
        if (chooseList.isEmpty()) {
            return Result.fail();
        }

        List<String> fileNames = EnclosureFilesUtils.uploadFiles(fileList);

        for (Choose choose : chooseList) {
            if (choose.getState() == 999 && type == 1) {
                // 需要是审核通过的订单才能作废
                choose.setIsCancel(true);
            } else if (choose.getState() == 999 && type == 2) {
                // 申请变更
                choose.setAlterationStatus(2);
            }
            choose.setState(1);
            choose.setExistEnclosure(true);
            choose.setEnclosureName(fileNames.get(0));
        }
        updateBatchById(chooseList);
        return Result.success();
    }

    @Override
    public void exportChooseList(String[] orderIds, String pid, int type, HttpServletResponse response) {
        SysUser sysUser = sysUserService.getUserInfo().getSysUser();
        List<SysRole> roleList = sysUserService.getUserInfo().getRoleList();

        List<ChooseExportDTO> chooseList;
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("pid", pid);

        if (type == 1) {
            if (roleList.stream().anyMatch(role -> role.getRoleName().contains("审核人"))) {
                queryMap.put("state", 2);
            } else {
                // 匹配人未提交状态订单
                queryMap.put("state", 1);
            }
        } else if (type == 2) {
            // 匹配人已提交状态订单
            queryMap.put("state", 2);
        } else if (type == 3) {
            // 匹配人已审批状态订单
            queryMap.put("state", 999);
        } else if (type == 4) {
            // 订单信息导出
            queryMap.put("create_id", sysUser.getUserId());
        }

        if (orderIds == null || orderIds.length < 1) {
            // 如果不传订单id，导出全部
            chooseList = exportChooseAll(queryMap);
        } else {
            // 根据订单id导出数据
            chooseList = exportChooseByIds(orderIds, queryMap);
        }

        // 下载
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            InputStream inputStream = FileUtils.getResources("exportExcel.xlsx");
            EasyExcelFactory.write(response.getOutputStream(), ChooseExportDTO.class).needHead(false).withTemplate(inputStream).sheet(0).doWrite(chooseList);
        } catch (Exception e) {
            log.error(e.toString());
            throw new CustomException(ResultCode.ABNORMAL.getMsg(), ResultCode.ABNORMAL.getCode());
        }
    }

    @Override
    public Result<Object> getOrderDetails(String orderId, Integer currentPage, Integer pageSize) {
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);

        Page<Choose> page = new Page<>(currentPage, pageSize);
        Page<Choose> choosePage = page(page, queryWrapper);
        List<Choose> chooseList = choosePage.getRecords();

        if (chooseList.isEmpty()) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = getChooseResultMap(chooseList);

        return Result.success(new PageData(result, new PageInfo(pageSize, currentPage, (int) choosePage.getTotal())));
    }

    @Override
    public Result<Object> updateChooseMatchTimeAndBatch(ChooseRequest chooseRequest) {
        String[] orderIds = chooseRequest.getIds();

        for (String orderId : orderIds) {
            QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);

            List<Choose> chooseList = list(queryWrapper);
            chooseList.forEach(updateChoose -> {
                updateChoose.setBatch(chooseRequest.getBatch());
                updateChoose.setMatchTime(chooseRequest.getMatchTime());
            });
            updateBatchById(chooseList);
        }

        return Result.success();

    }

    @Override
    public Result<Object> preserveChoose(ChooseRequest chooseRequest) {
        String orderId = chooseRequest.getOrderId();
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<Choose> chooseList = list(queryWrapper);

        for (Choose choose : chooseList) {
            if (choose.getAlterationStatus() == 1) {
                choose.setAlterationStatus(0);
            }
            choose.setReason("");
            choose.setIsCancelAudit(0);
            choose.setState(1);
        }
        updateBatchById(chooseList);
        return Result.success();
    }

    @Override
    public void exportApprovalForm(String pid, String[] orderIds, HttpServletResponse response) {
        SysUser sysUser = sysUserService.getUserInfo().getSysUser();

        String templateName = "approvalTemplate01";
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        XWPFDocument word = null;
        try {
            if (orderIds.length >= 1) {
                queryWrapper.in("order_id", orderIds);
            } else {
                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put("create_id", sysUser.getUserId());
                queryMap.put("pid", pid);
                // 分页查找登录用户创建的订单
                queryWrapper.ne("state", 0).allEq(queryMap).groupBy("order_id");
            }
            List<Choose> chooseAll = list(queryWrapper);
            BigDecimal price = new BigDecimal("0");
            for (Choose choose : chooseAll) {
                price = price.add(BigDecimal.valueOf(choose.getPrice()));
            }

            // 1、读取模板
            String informTemplateFile = exportWord;
            String ftlName = informTemplateFile + templateName + ".docx";
            File templateFile = new File(ftlName);
            word = new XWPFDocument(Files.newInputStream(templateFile.toPath()));

            // 2、实体--》map
            Map<String, String> params = new HashMap<>();
            Project project = projectService.getById(chooseAll.get(0).getPid());
            // 项目名称
            params.put("procurementPeople", project.getName());
            // 项目实施单位
            params.put("demandUnit", chooseAll.get(0).getDemandUnit());
            params.put("price", String.valueOf(price));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(chooseAll.get(0).getMatchingTime());
            // 日期
            params.put("matchingTime", calendar.get(Calendar.YEAR) + "-" + (1 + calendar.get(Calendar.MONTH)) + "-" + calendar.get(Calendar.DATE));

            // 3、替换数据
            // 3.1正文
            List<XWPFParagraph> paragraphs = word.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    String text = run.getText(0);
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        if (text.contains(entry.getKey())) {
                            run.setText(text.replaceAll(entry.getKey(), params.get(entry.getKey())), 0);
                        }
                    }
                }
            }

            // 3.2第一个表格
            XWPFTable xwpfTable1 = word.getTables().get(0);
            for (XWPFTableRow row : xwpfTable1.getRows()) {
                for (XWPFTableCell tableCell : row.getTableCells()) {
                    for (XWPFParagraph paragraph : tableCell.getParagraphs()) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            String text = run.getText(0);
                            for (Map.Entry<String, String> entry : params.entrySet()) {
                                if (text.contains(entry.getKey())) {
                                    run.setText(text.replaceAll(entry.getKey(), params.get(entry.getKey())), 0);
                                }
                            }
                        }
                    }
                }
            }

            // 序号  分标编号	分标名称	包号	工程名称	分包类型	项目单位	单位（项）	数量	匹配中标单位	分包金额（万元）	国网商城中标折扣率	中标折扣率	匹配金额（万元）	是否上国网商城	备注
            // 3.3第二个表格-匹配计划表
            XWPFTable xwpfTable2 = word.getTables().get(1);
            XWPFTableRow row2 = xwpfTable2.getRow(0);
            int rowIndex2 = 1;
            BigDecimal subtotal = new BigDecimal("0.0");
            for (Choose choose : chooseAll) {
                // 添加行
                copyRow(xwpfTable2, row2, rowIndex2);
                XWPFTableRow xwpfTableRow1 = xwpfTable2.getRow(rowIndex2);
                xwpfTableRow1.getCell(0).setText(String.valueOf(rowIndex2));
                xwpfTableRow1.getCell(1).setText(choose.getSubcontract());
                xwpfTableRow1.getCell(2).setText(choose.getSubcontracted());
                xwpfTableRow1.getCell(3).setText(choose.getPackageName());
                xwpfTableRow1.getCell(4).setText(choose.getProjectName());
                xwpfTableRow1.getCell(5).setText(choose.getChooseType());
                xwpfTableRow1.getCell(6).setText(choose.getDemandUnit());
                xwpfTableRow1.getCell(7).setText(choose.getUnit());
                xwpfTableRow1.getCell(8).setText(String.valueOf(choose.getQuantity()));
                xwpfTableRow1.getCell(9).setText(choose.getCompanyName());
                xwpfTableRow1.getCell(10).setText(choose.getPrice().toString());
                xwpfTableRow1.getCell(11).setText(choose.getShopBidDiscountRate());
                xwpfTableRow1.getCell(12).setText(choose.getBidDiscountRate());
                xwpfTableRow1.getCell(13).setText(choose.getSubtotal().toString());
                xwpfTableRow1.getCell(14).setText(choose.getRemarks());
                BigDecimal subtotal1 = choose.getSubtotal();
                subtotal = subtotal.add(subtotal1);
                rowIndex2++;
            }
            copyRow(xwpfTable2, row2, rowIndex2);
            XWPFTableRow row1 = xwpfTable2.getRow(rowIndex2);
            row1.getCell(0).setText("合计");
            row1.getCell(13).setText(subtotal.toString());

            // 3.4第三个表格-施工班组人员名单
            List<Choose> chooseList = getInfo(chooseAll);
            XWPFTable xwpfTable3 = word.getTables().get(2);
            XWPFTableRow row3 = xwpfTable3.getRow(1);
            int rowIndex3 = 2;
            for (Choose choose : chooseList) {
                List<Construction> constructionList = choose.getConstructionList();
                for (Construction construction : constructionList) {
                    // 添加行
                    copyRow(xwpfTable3, row3, rowIndex3);
                    XWPFTableRow xwpfTableRow3 = xwpfTable3.getRow(rowIndex3);
                    xwpfTableRow3.getCell(0).setText(choose.getSubcontract());
                    xwpfTableRow3.getCell(1).setText(choose.getSubcontracted());
                    xwpfTableRow3.getCell(2).setText(choose.getPackageName());
                    xwpfTableRow3.getCell(3).setText(choose.getDemandUnit());
                    xwpfTableRow3.getCell(4).setText(choose.getProjectName());
                    xwpfTableRow3.getCell(5).setText(choose.getChooseType());
                    xwpfTableRow3.getCell(6).setText(choose.getCompanyName());
                    xwpfTableRow3.getCell(7).setText(construction.getPost());
                    xwpfTableRow3.getCell(8).setText(construction.getName());
                    xwpfTableRow3.getCell(9).setText(construction.getSex());
                    xwpfTableRow3.getCell(10).setText(construction.getIdCard());
                    xwpfTableRow3.getCell(11).setText(construction.getPhone());
                    xwpfTableRow3.getCell(12).setText(construction.getRemark());
                    rowIndex3++;
                }
            }

            // 4、导出word
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(ftlName.getBytes(StandardCharsets.ISO_8859_1)));
            response.setContentType("octets/stream");
            word.write(response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (word != null) {
                    word.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void enclosureDisplay(HttpServletResponse response, String orderId) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            Choose choose = getOne(queryWrapper);

            String enclosureName = "";
            if (choose.getApproveEnclosure() != null && !choose.getApproveEnclosure().isEmpty() && choose.getState() == 999) {
                // 获取文件名称
                enclosureName = choose.getApproveEnclosure();
            } else {
                enclosureName = choose.getEnclosureName();
            }
            if (enclosureName == null || enclosureName.isEmpty()) {
                enclosureName = "没有附件.pdf";
            }
            // 读取文件
            inputStream = new BufferedInputStream(new FileInputStream(enclosureFile + enclosureName));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            // 将流传给前端
            outputStream.write(buffer);
        } catch (Exception e) {
            log.error(e.toString());
            throw new CustomException("没有找到附件", ResultCode.FAILED.getCode());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void generateTemplateZip(String[] orderIds, HttpServletResponse response) {
        String strDateFormat = "yyyy-MM-dd";

        List<String> pathList = new ArrayList<>();
        String templateName = "bidWinningNotice02";
        XWPFDocument word = null;
        try {
            QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("order_id", orderIds);
            List<Choose> chooseAll = list(queryWrapper);
            for (Choose choose : chooseAll) {
                if (Boolean.TRUE.equals(choose.getIsStatePrice())) {
                    // 国网模板
                    templateName = "bidWinningNotice01";
                }

                String ftlName = exportWord + templateName + ".docx";
                File templateFile = new File(ftlName);
                word = new XWPFDocument(Files.newInputStream(templateFile.toPath()));

                Project project = projectService.getById(choose.getPid());
                Map<String, String> params = new HashMap<>();

                params.put("subcontract", choose.getSubcontract());
                params.put("packageName", choose.getPackageName());
                params.put("subcontracted", choose.getSubcontracted());
                params.put("batch", choose.getBatch());
                params.put("orderNumber", choose.getOrdersNumber());

                params.put("companyName", choose.getCompanyName());
                params.put("projectName", project.getName());
                params.put("infoNumber", project.getInfoNumber());
                params.put("personName", choose.getPersonName());
                params.put("personTelephone", choose.getPersonTelephone());
                params.put("contacts", choose.getContacts());
                params.put("contactInformation", choose.getContactInformation());

                params.put("projectUnit", choose.getDemandUnit());
                params.put("matchTime", DateFormatUtils.format(choose.getMatchTime(), strDateFormat));

                params.put("name", choose.getProjectName());
                params.put("price", choose.getPrice().toString());
                params.put("bidDiscountRate", choose.getBidDiscountRate());
                params.put("shopBidDiscountRate", choose.getShopBidDiscountRate());
                params.put("subtotal", choose.getSubtotal().toString());
                params.put("purchaser", project.getProcurementPeople());
                params.put("institutions", project.getInstitutions());
                params.put("chooseType", choose.getChooseType());

                List<XWPFParagraph> paragraphs = word.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (XWPFRun run : runs) {
                        String text = run.getText(0);
                        for (Map.Entry<String, String> entry : params.entrySet()) {
                            if (text.contains(entry.getKey())) {
                                run.setText(text.replaceAll(entry.getKey(), params.get(entry.getKey())), 0);
                            }
                        }
                    }
                }

                // 3.2第一个表格
                XWPFTable xwpfTable1 = word.getTables().get(0);
                for (XWPFTableRow row : xwpfTable1.getRows()) {
                    for (XWPFTableCell tableCell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : tableCell.getParagraphs()) {
                            List<XWPFRun> runs = paragraph.getRuns();
                            for (XWPFRun run : runs) {
                                String text = run.getText(0);
                                for (Map.Entry<String, String> entry : params.entrySet()) {
                                    if (text.contains(entry.getKey())) {
                                        run.setText(text.replaceAll(entry.getKey(), params.get(entry.getKey())), 0);
                                    }
                                }
                            }
                        }
                    }
                }

                // 设置页眉页脚
                List<XWPFFooter> footerList = word.getFooterList();
                for (XWPFFooter footer : footerList) {
                    for (XWPFParagraph paragraph : footer.getParagraphs()) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            String text = run.getText(0);
                            for (Map.Entry<String, String> entry : params.entrySet()) {
                                if (text.contains(entry.getKey())) {
                                    run.setText(text.replaceAll(entry.getKey(), params.get(entry.getKey())), 0);
                                }
                            }
                        }
                    }
                }

                // 4、导出word
                String fileName = choose.getSubcontracted() + choose.getPackageName() + "-" + choose.getBatch() + "-" + choose.getOrdersNumber() + "-" + choose.getOrderId();
                String path = bidResultTable + fileName + ".docx";
                pathList.add(path);
                word.write(Files.newOutputStream(Paths.get(path)));
            }

            String zip = templateZip + "zt.zip";
            zipUtils.createZip(zip, pathList);
            zipUtils.downLoadFile(zip, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (word != null) {
                    word.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public Result<Object> getChooseQuotaInfo(String orderId) {
        HashMap<String, Object> resultMap = new HashMap<>();

        // 入围单位名称
        String companyName;
        // 预估金额
        Double estimatedAmount;
        // 已匹配金额
        BigDecimal matchingQuota = new BigDecimal("0");
        // 待匹配金额
        BigDecimal waitMatchingQuota = new BigDecimal("0");
        // 已匹配额度百分比
        BigDecimal matchingPercentage;
        // 待匹配额度百分比
        BigDecimal waitMatchingPercentage;

        QueryWrapper<Choose> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("order_id", orderId);
        Choose queryChoose = list(queryWrapper1).get(0);

        companyName = queryChoose.getCompanyName();
        estimatedAmount = Double.parseDouble(queryChoose.getEstimatedAmount());

        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("subcontracted", queryChoose.getSubcontracted());
        queryMap.put("package_name", queryChoose.getPackageName());
        queryMap.put("company_name", companyName);
        queryMap.put("is_cancel", 0);
        QueryWrapper<Choose> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.allEq(queryMap).notIn("state", 0, -1).ne("is_cancel", 1);
        List<Choose> chooseList = list(queryWrapper2);

        for (Choose choose : chooseList) {
            if (choose.getState() == 999) {
                matchingQuota = matchingQuota.add(choose.getSubtotal());
            } else {
                waitMatchingQuota = waitMatchingQuota.add(choose.getSubtotal());
            }
        }
        matchingPercentage = matchingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.CEILING).multiply(BigDecimal.valueOf(100));
        waitMatchingPercentage = waitMatchingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.CEILING).multiply(BigDecimal.valueOf(100));

        resultMap.put("companyName", companyName);
        resultMap.put("estimatedAmount", estimatedAmount);
        resultMap.put("matchingQuota", matchingQuota);
        resultMap.put("matchingPercentage", matchingPercentage.divide(BigDecimal.valueOf(1), 2, RoundingMode.CEILING).toString());
        resultMap.put("waitMatchingQuota", waitMatchingQuota);
        resultMap.put("waitMatchingPercentage", waitMatchingPercentage.divide(BigDecimal.valueOf(1), 2, RoundingMode.CEILING).toString());
        return Result.success(resultMap);
    }

    @Override
    public List<Map<String, String>> queryBatch(String pid) {
        List<Map<String, String>> list = new ArrayList<>();
        List<String> bathStr = baseMapper.queryBatch(pid);
        bathStr.forEach(str -> {
            Map<String, String> map = new HashMap<>();
            map.put("text", str);
            map.put("value", str);
            list.add(map);
        });
        return list;
    }

    @Override
    public List<Map<String, String>> querySubcontracted(String pid) {
        List<Map<String, String>> list = new ArrayList<>();
        List<String> bathStr = baseMapper.querySubcontracted(pid);
        bathStr.forEach(str -> {
            Map<String, String> map = new HashMap<>();
            map.put("text", str);
            map.put("value", str);
            list.add(map);
        });
        return list;
    }

    @Override
    public Result<Object> queryStatistics(String pid, Integer currentPage, Integer pageSize, Integer type, String batch, String demandUnit, String packageName, String subcontract, String subcontracted, String startTime, String endTime) {
        // 1、分页条件查找数据
        List<Choose> chooseList = getChoosePage(pid, currentPage, pageSize, type, batch, demandUnit, packageName, subcontract, subcontracted, startTime, endTime);

        // 1.1、如果没有找到数据，直接返回空集合
        if (chooseList.isEmpty()) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        // 2、封装数据
        for (Choose choose : chooseList) {
            // 预估金额
            double estimatedAmount;
            // 已匹配金额
            BigDecimal matchingQuota = new BigDecimal("0");
            // 待匹配金额
            BigDecimal waitMatchingQuota = new BigDecimal("0");
            // 剩余金额
            BigDecimal remainingQuota;
            // 已匹配额度百分比
            BigDecimal matchingPercentage;
            // 待匹配额度百分比
            BigDecimal waitMatchingPercentage;
            // 剩余额度百分比
            BigDecimal remainingPercentage;

            // 2.1、根据条件查找数据（最少一条）
            List<Choose> chooses = getChooses(choose);

            // 2.2、填充数据
            if (type != 4) {
                // 除了”已匹配清单“模块，其他都是没有数据完整数据的
                BeanUtil.copyProperties(chooses.get(0), choose);
                choose.setName(projectService.getById(chooses.get(0).getPid()).getName());
            }

            estimatedAmount = Double.parseDouble(choose.getEstimatedAmount());

            // 2.3、查找额度比例
            Double quota = getQuota(choose);

            // 3、计算相关额度
            for (Choose c : chooses) {
                if (c.getState() == 999) {
                    // 3.1、如果是已通过，已匹配金额累加
                    matchingQuota = matchingQuota.add(c.getSubtotal());
                } else {
                    // 3.2、如果是已通过，未匹配金额累加
                    waitMatchingQuota = waitMatchingQuota.add(c.getSubtotal());
                }
            }
            // 3.4、计算剩余金额
            remainingQuota = BigDecimal.valueOf(estimatedAmount * quota / 100).subtract(matchingQuota.add(waitMatchingQuota));

            matchingPercentage = matchingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100));
            waitMatchingPercentage = waitMatchingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100));
            remainingPercentage = remainingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100));

            if (type == 3) {
                choose.setEstimatedAmount("/");
                choose.setMatchingPercentage("/");
            } else {
                choose.setEstimatedAmount(String.valueOf(estimatedAmount));
                choose.setMatchingPercentage(matchingPercentage.stripTrailingZeros().toPlainString() + "%");

            }
            choose.setMatchingQuota(matchingQuota.doubleValue());
            choose.setWaitMatchingQuota(waitMatchingQuota.doubleValue());
            choose.setWaitMatchingPercentage(waitMatchingPercentage.stripTrailingZeros().toPlainString() + "%");
            choose.setRemainingQuota(remainingQuota.doubleValue());
            choose.setRemainingPercentage(remainingPercentage.stripTrailingZeros().toPlainString() + "%");

        }

        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = getChooseResultMap(chooseList);

        return Result.success(new PageData(result, new PageInfo(pageSize, currentPage, chooseList.size())));
    }

    /**
     * 统计分析：根据条件查找额度比例
     *
     * @param choose 条件参数
     * @return 额度
     */
    private Double getQuota(Choose choose) {
        QueryWrapper<AnswerQuote> answerQuoteQueryWrapper = new QueryWrapper<>();
        HashMap<String, Object> queryMap3 = new HashMap<>();
        queryMap3.put("subcontracted", choose.getSubcontracted());
        queryMap3.put("package_name", choose.getPackageName());
        queryMap3.put("company_name", choose.getCompanyName());
        answerQuoteQueryWrapper.allEq(queryMap3);
        AnswerQuote answerQuote = answerQuoteService.getOne(answerQuoteQueryWrapper);
        // 额度比例
        return answerQuote.getQuotaState() == 1 ? answerQuote.getQuotaMin() : (answerQuote.getQuotaState() == 2 ? answerQuote.getQuotaStandard() : answerQuote.getQuotaMax());
    }

    /**
     * 统计分析：根据条件查找数据
     *
     * @param choose 条件参数
     * @return 数据集合
     */
    private List<Choose> getChooses(Choose choose) {
        Map<String, Object> beanMap = BeanUtil.beanToMap(choose);
        Map<String, Object> queryMap = new HashMap<>();
        // 排空并转key为下划线
        beanMap.entrySet().stream().filter(entry -> ObjectUtil.isNotNull(entry.getValue())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).forEach((k, v) -> queryMap.put(CharSequenceUtil.toUnderlineCase(k), v));
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap).notIn("state", 0, -1).ne("is_cancel", 1);
        return list(queryWrapper);
    }

    /**
     * 统计分析：分页条件查找基础数据
     */
    private List<Choose> getChoosePage(String pid, Integer currentPage, Integer pageSize, Integer type, String batch, String demandUnit, String packageName, String subcontract, String subcontracted, String startTime, String endTime) {
        HashMap<String, Object> chooseMap = new HashMap<>();
        chooseMap.put("pid", pid);
        chooseMap.put("batch", batch);
        chooseMap.put("demand_unit", demandUnit);
        chooseMap.put("package_name", packageName);
        chooseMap.put("subcontract", subcontract);
        chooseMap.put("subcontracted", subcontracted);

        // 去除值空地查询条件
        chooseMap.values().removeAll(Collections.singleton(null));

        QueryWrapper<Choose> chooseQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(startTime)) {
            chooseQueryWrapper.ge("order_time", startTime);
        }
        if (ObjectUtil.isNotNull(endTime)) {
            chooseQueryWrapper.le("order_time", endTime);
        }

        if (type == 1) {
            // 分标名称统计
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, package_name, company_name").orderByAsc("subcontracted");
        } else if (type == 2) {
            // 入围单位统计
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, package_name, company_name").orderByAsc("company_name");
        } else if (type == 3) {
            // 需求单位统计
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, demand_unit").orderByAsc("demand_unit");
        } else if (type == 4) {
            // 已匹配清单统计
            chooseQueryWrapper.eq("state", 999);
        } else if (type == 5) {
            // 匹配批次统计
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, package_name, company_name, demand_unit, batch").orderByAsc("batch");
        } else if (type == 6) {
            // 总批次统计
            chooseQueryWrapper.select("DISTINCT pid, batch");
        }

        chooseQueryWrapper.allEq(chooseMap).notIn("state", 0, -1).ne("is_cancel", 1);

        Page<Choose> page = new Page<>(currentPage, pageSize);
        Page<Choose> choosePage = page(page, chooseQueryWrapper);
        return choosePage.getRecords();
    }

    @Override
    public void exportStatistics(String pid, Integer type, Choose queryChoose, HttpServletResponse response) {
        String strDateFormat = "yyyy-MM-dd";

        String fileName = "exportExcel1.xlsx";

        HashMap<String, Object> chooseMap = new HashMap<>();
        chooseMap.put("pid", pid);
        chooseMap.put("batch", queryChoose.getBatch());
        chooseMap.put("demand_unit", queryChoose.getDemandUnit());
        chooseMap.put("package_name", queryChoose.getPackageName());
        chooseMap.put("subcontract", queryChoose.getSubcontract());
        chooseMap.put("subcontracted", queryChoose.getSubcontracted());

        // 去除值空地查询条件
        chooseMap.values().removeAll(Collections.singleton(null));

        QueryWrapper<Choose> chooseQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(queryChoose.getStartTime())) {
            chooseQueryWrapper.ge("order_time", queryChoose.getStartTime());
        }
        if (ObjectUtil.isNotNull(queryChoose.getEndTime())) {
            chooseQueryWrapper.le("order_time", queryChoose.getEndTime());
        }

        if (type == 1) {
            // 分标名称统计
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, package_name, company_name");
        } else if (type == 2) {
            // 入围单位统计
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, package_name, company_name");
        } else if (type == 3) {
            // 需求单位统计
            fileName = "exportExcel2.xlsx";
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, demand_unit");
        } else if (type == 4) {
            // 已匹配清单统计
            fileName = "exportExcel3.xlsx";
            chooseQueryWrapper.eq("state", 999);
        } else if (type == 5) {
            // 已匹配清单统计
            fileName = "exportExcel4.xlsx";
            chooseQueryWrapper.select("DISTINCT pid, subcontracted, package_name, company_name, demand_unit, batch");

        } else if (type == 6) {
            // 总批次统计
            fileName = "exportExcel5.xlsx";
            chooseQueryWrapper.select("DISTINCT pid, batch");
        }

        chooseQueryWrapper.allEq(chooseMap).notIn("state", 0, -1).ne("is_cancel", 1);
        List<Choose> chooseList = list(chooseQueryWrapper);

        for (Choose choose : chooseList) {
            // 预估金额
            double estimatedAmount;
            // 已匹配金额
            BigDecimal matchingQuota = new BigDecimal("0");
            // 待匹配金额
            BigDecimal waitMatchingQuota = new BigDecimal("0");
            // 剩余金额
            BigDecimal remainingQuota;
            // 已匹配额度百分比
            BigDecimal matchingPercentage;
            // 待匹配额度百分比
            BigDecimal waitMatchingPercentage;
            // 剩余额度百分比
            BigDecimal remainingPercentage;

            Map<String, Object> beanMap = BeanUtil.beanToMap(choose);
            Map<String, Object> queryMap = new HashMap<>();

            // 排空并转key为下划线
            beanMap.entrySet().stream().filter(entry -> entry.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).forEach((k, v) -> queryMap.put(CharSequenceUtil.toUnderlineCase(k), v));

            QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
            queryWrapper.allEq(queryMap).notIn("state", 0, -1).ne("is_cancel", 1);

            List<Choose> chooses = list(queryWrapper);
            if (type != 4) {
                // 除了”已匹配清单“模块，其他都是没有数据完整数据的
                BeanUtil.copyProperties(chooses.get(0), choose);
                choose.setName(projectService.getById(chooses.get(0).getPid()).getName());
            }

            estimatedAmount = Double.parseDouble(choose.getEstimatedAmount());

            // 查找额度比例
            Double quota = getQuota(choose);

            // 计算相关额度
            for (Choose c : chooses) {
                if (c.getState() == 999) {
                    // 如果是已通过，已匹配金额累加
                    matchingQuota = matchingQuota.add(c.getSubtotal());
                } else {
                    // 如果是已通过，未匹配金额累加
                    waitMatchingQuota = waitMatchingQuota.add(c.getSubtotal());
                }
            }
            remainingQuota = BigDecimal.valueOf(estimatedAmount * quota / 100).subtract(matchingQuota.add(waitMatchingQuota));

            matchingPercentage = matchingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100));
            waitMatchingPercentage = waitMatchingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100));
            remainingPercentage = remainingQuota.divide(BigDecimal.valueOf(estimatedAmount), 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100));

            if (type == 3) {
                choose.setEstimatedAmount("/");
                choose.setMatchingPercentage("/");
            } else {
                choose.setEstimatedAmount(String.valueOf(estimatedAmount));
                choose.setMatchingPercentage(matchingPercentage.divide(BigDecimal.valueOf(1), 2, RoundingMode.CEILING).stripTrailingZeros().toPlainString() + "%");
            }

            choose.setMatchingQuota(matchingQuota.doubleValue());
            choose.setWaitMatchingQuota(waitMatchingQuota.doubleValue());
            choose.setWaitMatchingPercentage(waitMatchingPercentage.divide(BigDecimal.valueOf(1), 2, RoundingMode.CEILING).stripTrailingZeros().toPlainString() + "%");
            choose.setRemainingQuota(remainingQuota.doubleValue());
            choose.setRemainingPercentage(remainingPercentage.divide(BigDecimal.valueOf(1), 2, RoundingMode.CEILING).stripTrailingZeros().toPlainString() + "%");
        }

        // 下载
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            InputStream inputStream = FileUtils.getResources(fileName);

            if (type == 1 || type == 2) {
                // 分标名称统计
                List<ExportStatistics1> exportStatistics1List = new ArrayList<>();
                chooseList.forEach(choose1 -> {
                    ExportStatistics1 exportStatistics1 = BeanUtil.copyProperties(choose1, ExportStatistics1.class);
                    StringBuilder time = new StringBuilder();
                    if (ObjectUtil.isNotNull(queryChoose.getStartTime())) {
                        time.append(DateFormatUtils.format(queryChoose.getStartTime(), strDateFormat)).append("/");
                    }
                    if (ObjectUtil.isNotNull(queryChoose.getEndTime())) {
                        time.append(DateFormatUtils.format(queryChoose.getEndTime(), strDateFormat));
                    }
                    exportStatistics1.setTime(time.toString());
                    exportStatistics1List.add(exportStatistics1);
                });
                EasyExcelFactory.write(response.getOutputStream(), ExportStatistics1.class).needHead(false).withTemplate(inputStream).sheet(0).doWrite(exportStatistics1List);
            } else if (type == 3) {
                // 需求单位统计
                List<ExportStatistics2> exportStatistics2List = new ArrayList<>();
                chooseList.forEach(choose2 -> {
                    ExportStatistics2 exportStatistics2 = BeanUtil.copyProperties(choose2, ExportStatistics2.class);
                    StringBuilder time = new StringBuilder();
                    if (ObjectUtil.isNotNull(queryChoose.getStartTime())) {
                        time.append(DateFormatUtils.format(queryChoose.getStartTime(), strDateFormat)).append("/");
                    }
                    if (ObjectUtil.isNotNull(queryChoose.getEndTime())) {
                        time.append(DateFormatUtils.format(queryChoose.getEndTime(), strDateFormat));
                    }
                    exportStatistics2.setTime(time.toString());
                    exportStatistics2List.add(exportStatistics2);
                });
                EasyExcelFactory.write(response.getOutputStream(), ExportStatistics2.class).needHead(false).withTemplate(inputStream).sheet(0).doWrite(exportStatistics2List);
            } else if (type == 4) {
                // 匹配批次统计
                List<ExportStatistics3> exportStatistics3List = new ArrayList<>();
                chooseList.forEach(choose3 -> {
                    ExportStatistics3 exportStatistics3 = BeanUtil.copyProperties(choose3, ExportStatistics3.class);
                    exportStatistics3.setIsCancel(Boolean.TRUE.equals(choose3.getIsCancel()) ? "是" : "否");
                    exportStatistics3.setIsStatePrice(Boolean.TRUE.equals(choose3.getIsStatePrice()) ? "是" : "否");
                    exportStatistics3.setPriceCeiling(choose3.getSubtotal().toString());
                    exportStatistics3List.add(exportStatistics3);
                });
                EasyExcelFactory.write(response.getOutputStream(), ExportStatistics3.class).needHead(false).withTemplate(inputStream).sheet(0).doWrite(exportStatistics3List);
            } else if (type == 5) {
                // 已匹配清单统计
                List<ExportStatistics4> exportStatistics4List = new ArrayList<>();
                chooseList.forEach(choose4 -> {
                    ExportStatistics4 exportStatistics4 = BeanUtil.copyProperties(choose4, ExportStatistics4.class, "match_time");
                    StringBuilder time = new StringBuilder();
                    if (ObjectUtil.isNotNull(queryChoose.getStartTime())) {
                        time.append(DateFormatUtils.format(queryChoose.getStartTime(), strDateFormat)).append("/");
                    }
                    if (ObjectUtil.isNotNull(queryChoose.getEndTime())) {
                        time.append(DateFormatUtils.format(queryChoose.getEndTime(), strDateFormat));
                    }
                    exportStatistics4.setTime(time.toString());
                    exportStatistics4.setMatchTime(DateFormatUtils.format(choose4.getMatchTime(), strDateFormat));
                    exportStatistics4List.add(exportStatistics4);
                });
                EasyExcelFactory.write(response.getOutputStream(), ExportStatistics4.class).needHead(false).withTemplate(inputStream).sheet(0).doWrite(exportStatistics4List);
            } else if (type == 6) {
                // 总批次统计
                List<ExportStatistics5> exportStatistics5List = new ArrayList<>();
                chooseList.forEach(choose5 -> exportStatistics5List.add(BeanUtil.copyProperties(choose5, ExportStatistics5.class)));
                EasyExcelFactory.write(response.getOutputStream(), ExportStatistics5.class).needHead(false).withTemplate(inputStream).sheet(0).doWrite(exportStatistics5List);
            }

        } catch (Exception e) {
            log.error(e.toString());
            throw new CustomException(ResultCode.ABNORMAL.getMsg(), ResultCode.ABNORMAL.getCode());
        }

    }

    @Override
    public Result<Object> fallbackChoose(ChooseRequest chooseRequest) {
        String[] orderIds = chooseRequest.getIds();

        for (String orderId : orderIds) {
            QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);

            List<Choose> chooseList = list(queryWrapper);
            chooseList.forEach(updateChoose -> {
                updateChoose.setState(chooseRequest.getState());
            });
            updateBatchById(chooseList);
        }

        return Result.success();
    }

    /**
     * 把实体字段换成动态表格标准
     */
    private List<Map<String, Object>> getProjectResultMap(List<Project> projectList) {
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = new ArrayList<>();
        for (Project project : projectList) {
            Map<String, Object> map = new HashMap<>();
            Field[] fields = project.getClass().getDeclaredFields();
            for (Field field : fields) {
                try {
                    // 这个是，有的字段是用private修饰的 将他设置为可读
                    field.setAccessible(true);
                    String fieldsName = "p_project_" + FieldsUtils.humpToUnderline(field.getName());
                    Object fieldsValue = field.get(project);
                    map.put(fieldsName, fieldsValue);
                } catch (Exception e) {
                    throw new CustomException(e);
                }
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 把实体字段换成动态表格标准
     */
    private List<Map<String, Object>> getChooseResultMap(List<Choose> chooseList) {
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = new ArrayList<>();
        for (Choose choose : chooseList) {
            Map<String, Object> map = new HashMap<>();
            Field[] fields = choose.getClass().getDeclaredFields();
            for (Field field : fields) {
                try {
                    // 这个是，有的字段是用private修饰的 将他设置为可读
                    field.setAccessible(true);
                    String fieldsName = "t_choose_" + FieldsUtils.humpToUnderline(field.getName());
                    if ("t_choose_name".equals(fieldsName)) {
                        fieldsName = "p_project_name";
                    }
                    Object fieldsValue = field.get(choose);
                    map.put(fieldsName, fieldsValue);
                } catch (Exception e) {
                    throw new CustomException(e);
                }
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 用于word表格深克隆行
     */
    private void copyRow(XWPFTable xwpfTable, XWPFTableRow sourceRow, int rowIndex) {
        XWPFTableRow targetRow = xwpfTable.insertNewTableRow(rowIndex);
        targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr());

        List<XWPFTableCell> tableCells = sourceRow.getTableCells();
        if (tableCells.isEmpty()) {
            return;
        }

        XWPFTableCell targetCell;
        for (XWPFTableCell cell : tableCells) {
            targetCell = targetRow.addNewTableCell();
            targetCell.getCTTc().setTcPr(cell.getCTTc().getTcPr());
            targetCell.getParagraphs().get(0).getCTP().setPPr(cell.getParagraphs().get(0).getCTP().getPPr());
        }

    }

    // 导出全部数据
    private List<ChooseExportDTO> exportChooseAll(Map<String, Object> queryMap) {
        List<ChooseExportDTO> chooseExportDTOList = new ArrayList<>();

        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap).ne("state", 0);
        List<Choose> chooseList = list(queryWrapper);

        for (Choose choose : chooseList) {
            // 待匹配金额
            BigDecimal waitMatchingQuota = new BigDecimal("0");
            HashMap<String, Object> queryMap3 = new HashMap<>();
            queryMap3.put("subcontracted", choose.getSubcontracted());
            queryMap3.put("package_name", choose.getPackageName());
            queryMap3.put("company_name", choose.getCompanyName());
            QueryWrapper<Choose> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.allEq(queryMap3).notIn("state", 0, -1).ne("is_cancel", 1);
            List<Choose> chooses = list(queryWrapper3);
            for (Choose c : chooses) {
                if (c.getState() == 1 || c.getState() == 2) {
                    waitMatchingQuota = waitMatchingQuota.add(c.getSubtotal());
                }
            }

            ChooseExportDTO chooseExportDTO = BeanUtil.copyProperties(choose, ChooseExportDTO.class);
            chooseExportDTO.setMatchingQuota(waitMatchingQuota.doubleValue());
            chooseExportDTO.setCancel(Boolean.TRUE.equals(choose.getIsCancel()) ? "是" : "否");
            chooseExportDTO.setStatus((choose.getState() == 1 || choose.getState() == 2) ? "待审核" : (choose.getState() == 999 ? "审核通过" : (choose.getState() == -1 ? "已驳回" : "")));
            chooseExportDTOList.add(chooseExportDTO);
        }

        return chooseExportDTOList;
    }

    // 导出选择的数据
    private List<ChooseExportDTO> exportChooseByIds(String[] orderIds, Map<String, Object> queryMap) {
        List<Choose> chooseList = new ArrayList<>();
        List<ChooseExportDTO> chooseExportDTOList = new ArrayList<>();

        for (String orderId : orderIds) {
            queryMap.put("order_id", orderId);
            QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();
            queryWrapper.allEq(queryMap);
            chooseList.addAll(list(queryWrapper));
        }

        for (Choose choose : chooseList) {
            // 待匹配金额
            BigDecimal waitMatchingQuota = new BigDecimal("0");
            HashMap<String, Object> queryMap3 = new HashMap<>();
            queryMap3.put("subcontracted", choose.getSubcontracted());
            queryMap3.put("package_name", choose.getPackageName());
            queryMap3.put("company_name", choose.getCompanyName());
            QueryWrapper<Choose> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.allEq(queryMap3).notIn("state", 0, -1).ne("is_cancel", 1);
            List<Choose> chooses = list(queryWrapper3);
            for (Choose c : chooses) {
                if (c.getState() == 1 || c.getState() == 2) {
                    waitMatchingQuota = waitMatchingQuota.add(c.getSubtotal());
                }
            }

            ChooseExportDTO chooseExportDTO = BeanUtil.copyProperties(choose, ChooseExportDTO.class);
            chooseExportDTO.setMatchingQuota(waitMatchingQuota.doubleValue());
            chooseExportDTO.setCancel(Boolean.TRUE.equals(choose.getIsCancel()) ? "是" : "否");
            chooseExportDTO.setStatus((choose.getState() == 1 || choose.getState() == 2) ? "待审核" : (choose.getState() == 999 ? "审核通过" : (choose.getState() == -1 ? "已驳回" : "")));
            chooseExportDTOList.add(chooseExportDTO);
        }
        return chooseExportDTOList;
    }

    // 匹配人员查看
    public Result<Object> getMatchingChoose(String pid, Integer currentPage, Integer pageSize, int type, Map<String, Object> queryMap) {

        if (type == 1) {
            // 匹配人未提交状态订单
            queryMap.put("state", 1);   // 用户待审核状态订单
            return returnChoose(pid, currentPage, pageSize, queryMap);
        } else if (type == 2) {
            // 匹配人已提交状态订单
            queryMap.put("state", 2);
            return returnChoose(pid, currentPage, pageSize, queryMap);
        } else if (type == 3) {
            // 匹配人已审批状态订单
            queryMap.put("state", 999);
            return returnChoose(pid, currentPage, pageSize, queryMap);
        }

        return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
    }

    // 审核人员查看
    public Result<Object> getAuditChoose(String pid, Integer currentPage, Integer pageSize, int type, Map<String, Object> queryMap) {

        if (type == 1) {
            // 审核人未提交状态订单
            queryMap.put("state", 2);   // 匹配人已提交状态订单
            return returnChoose(pid, currentPage, pageSize, queryMap);
        } else if (type == 3) {
            // 审核人已审批状态订单
            queryMap.put("state", 999);
            return returnChoose(pid, currentPage, pageSize, queryMap);
        }

        return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
    }

    // 代理机构查看
    private Result<Object> getAgencyChoose(String pid, Integer currentPage, Integer pageSize, int type, Map<String, Object> queryMap) {

        if (type == 1) {
            // 匹配人未提交状态订单
            queryMap.put("state", 1);
            return returnChoose(pid, currentPage, pageSize, queryMap);
        } else if (type == 2) {
            // 匹配人已提交状态订单
            queryMap.put("state", 2);
            return returnChoose(pid, currentPage, pageSize, queryMap);
        } else if (type == 3) {
            // 匹配人已审批状态订单
            queryMap.put("state", 999);
            return returnChoose(pid, currentPage, pageSize, queryMap);
        }

        return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
    }

    /**
     * 获取登录用户的需求单位名称
     */
    public String getDemandUnitName() {
        UserHolder userInfo = sysUserService.getUserInfo();
        SysUser sysUser = userInfo.getSysUser();

        SysUserDemand sysUserDemand = sysUserDemandService.getOne(new QueryWrapper<SysUserDemand>().eq("user_id", sysUser.getUserId()));

        if (sysUserDemand == null) {
            return "";
        }
        DemandUnit demandUnit = demandUnitService.getOne(new QueryWrapper<DemandUnit>().eq("id", sysUserDemand.getDemandUnitId()));
        return demandUnit.getDemandUnitName();
    }

    /**
     * 查找订单
     *
     * @param pid         项目id
     * @param currentPage 当前页
     * @param pageSize    页面大小
     * @param queryMap    条件
     * @return 结果值
     */
    private Result<Object> returnChoose(String pid, Integer currentPage, Integer pageSize, Map<String, Object> queryMap) {
        // 传pid又放进参数queryMap??????????????????? 脱裤子放屁  程序员的脸都没了
        queryMap.put("pid", pid);
        // 去除值空地查询条件
        queryMap.values().removeAll(Collections.singleton(null));

        // 分页查找登录用户创建的订单
        QueryWrapper<Choose> queryWrapper = new QueryWrapper<>();

//        queryWrapper.ne("state", 0).allEq(queryMap).groupBy("order_id");
        queryWrapper.ne("state", 0).allEq(queryMap);
        Page<Choose> page = new Page<>(currentPage, pageSize);
        Page<Choose> choosePage = page(page, queryWrapper);
        List<Choose> chooseList = choosePage.getRecords();

        if (chooseList.isEmpty()) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, (int) choosePage.getTotal())));
        }

        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = getChooseResultMap(chooseList);

        //临时处理，不想改别人的老代码，增加一个字段控制前端的是否生成了二次议价
        for (Map<String, Object> map : result) {
            map.put("is_second_bargain", secondBargainService.count(new QueryWrapper<SecondBargain>().eq("order_id", map.get("t_choose_id").toString())));
        }

        return Result.success(new PageData(result, new PageInfo(pageSize, currentPage, (int) choosePage.getTotal())));
    }

    /**
     * 组装班组人员
     */
    private List<Choose> getInfo(List<Choose> chooseList) {
        for (Choose choose : chooseList) {
            List<Construction> constructionList = new ArrayList<>();
            String chooseId = choose.getId();
            QueryWrapper<ChooseConstruction> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("choose_id", chooseId);

            List<ChooseConstruction> chooseConstructionList = chooseConstructionService.list(queryWrapper1);

            for (ChooseConstruction chooseConstruction : chooseConstructionList) {
                String constructionId = chooseConstruction.getConstructionId();
                QueryWrapper<Construction> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("id", constructionId);
                constructionList.add(constructionService.getOne(queryWrapper2));
            }
            choose.setConstructionList(constructionList);
        }
        return chooseList;
    }

}